package work.month06.day09;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * @date 2020/06/09
 * @author 王光浩
 * @introduction 自定义一个实现 Set 接口的类，该类需要实现 Set 接口中的所有方法。（具体实现可以参照 HashSet实现类）
 */
public class MySet<E> implements Set<E>{

// ================  实例字段   ==================================
	private transient HashMap<E,Object> myMap;
	private static Object present = new Object();
	
// ================  构造方法  ===================================
	
	/**
	 * 无参的构造方法，默认容量为 16，装载因子值为 0.75
	 */
	public MySet() {
		myMap = new HashMap<>();
	}
	
	/**
	 * 使用指定的容量和默认的装载因子初始化 MySet
	 * @param initialCapacity
	 */
	public MySet(int initialCapacity) {
		myMap = new HashMap<>(initialCapacity);
	}
	
	/**
	 * 使用指定的容量和默认的装载因子初始化 MySet
	 * @param initialCapacity 指定初始化的容量
	 * @param loadFactor 指定的装载因子
	 */
	public MySet(int initialCapacity, float loadFactor) {
		myMap = new HashMap<>(initialCapacity, loadFactor);
	}
	
	/**
	 * 使用指定的集合来创建对应的 MySet集合
	 * @param c
	 */
	public MySet(Collection<? extends E> c) {
		myMap = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
	}
	
	@Override
	public int size() {
		return myMap.size();
	}

	@Override
	public boolean isEmpty() {
		return myMap.isEmpty();
	}

	@Override
	public boolean contains(Object o) {
		return myMap.containsKey(o);
	}

	@Override
	public Iterator<E> iterator() {
		return myMap.keySet().iterator();
	}

	@Override
	public Object[] toArray() {
		return myMap.keySet().toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return myMap.keySet().toArray(a);
	}

	@Override
	public boolean add(E e) {
		return myMap.put(e, present) == null;
	}

	@Override
	public boolean remove(Object o) {
		return myMap.remove(o) != null;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return myMap.keySet().containsAll(c);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		final int size = myMap.size();
		for ( E e : c) {
			add(e);
		}
		return size == myMap.size();
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return myMap.keySet().retainAll(c);
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return myMap.keySet().removeAll(c);
	}

	@Override
	public void clear() {	
		myMap.clear();
	}

	@Override
	public String toString() {
		return myMap.keySet().toString();
	}
}
